package io.renren.controller;

import io.renren.common.exception.RRException;
import io.renren.common.utils.ConfigConstant;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.HttpClientUtils;
import io.renren.common.utils.HttpContextUtils;
import io.renren.common.utils.IPUtils;
import io.renren.common.utils.ProjectConstant;
import io.renren.common.utils.R;
import io.renren.common.utils.SMSManages;
import io.renren.common.utils.SpringContextUtils;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.entity.MemberEntity;
import io.renren.entity.PhoneCodeEntity;
import io.renren.form.CaptchaForm;
import io.renren.form.ForgotPwdForm;
import io.renren.form.RegisterForm;
import io.renren.service.MemberService;
import io.renren.service.PhoneCodeService;
import io.renren.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;

/**
 * 注册接口
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 17:27
 */
@RestController
@RequestMapping("/api")
@Api(tags = "注册接口")
public class ApiRegisterController extends AbstractController {

	@Autowired
	MemberService memberService;

	@Autowired
	PhoneCodeService phoneCodeService;

	@Autowired
	SysConfigService sysConfigService;

	@PostMapping("send")
	@ApiOperation("发送短信")
	public R send(@RequestBody CaptchaForm form) {
		// 表单校验
		ValidatorUtils.validateEntity(form);
		form.setMobile(StringUtils.deleteWhitespace(form.getMobile()));
		Assert.isTrue(toTencent(form.getTicket(), form.getRandstr()), "验证失败");
		boolean exists = memberService.selectCount(new EntityWrapper<MemberEntity>().eq("mobile", form.getMobile())) == 1;
		if (form.getType() == ProjectConstant.PHONECODE_TYPE_REG) {
			Assert.isTrue(!exists, "手机号已注册");
		} else {
			Assert.isTrue(exists, "手机号尚未注册");
		}
		Date now = new Date();
		int sendCount = phoneCodeService.selectCount(new EntityWrapper<PhoneCodeEntity>().eq("mobile", form.getMobile()).eq("type", form.getType())
				.ge("create_time", DateUtils.getStartOfDay(now)));
		int sendMax = sysConfigService.getValueI(ConfigConstant.PHONE_CODE_REG);
		Assert.isTrue(sendCount < sendMax, "短信发送次数过多");

		String captcha = RandomStringUtils.randomNumeric(4);
		/*********** 发送短信验证 **********/
		SMSManages sms = new SMSManages(sysConfigService.getValue(ConfigConstant.SMS_USER), sysConfigService.getValue(ConfigConstant.SMS_PWD),
				sysConfigService.getValue(ConfigConstant.SMS_VERY_CODE));
		String retCode = sms.sendSMS(form.getMobile(), "JSM42425-0001", "@1@=" + captcha);
		logger.info("retCode：" + retCode);

		// 保存数据库
		PhoneCodeEntity phoneCode = new PhoneCodeEntity();
		phoneCode.setCaptcha(captcha);
		phoneCode.setMobile(form.getMobile());
		phoneCode.setType(form.getType());
		phoneCode.setExpireTime(DateUtils.addDateMinutes(now, 5));// 5分钟
		phoneCode.setCreateTime(now);
		phoneCodeService.insert(phoneCode);

		return R.ok();
	}

	@PostMapping("register")
	@ApiOperation("注册")
	public R register(@RequestBody RegisterForm form) {
		// 表单校验
		ValidatorUtils.validateEntity(form);
		form.setMobile(StringUtils.deleteWhitespace(form.getMobile()));
		memberService.save(form);
		return R.ok();
	}

	@PostMapping("forgotPwd")
	@ApiOperation("找回密码")
	public R forgotPwd(@RequestBody ForgotPwdForm form) {
		// 表单校验
		ValidatorUtils.validateEntity(form);
		// 手机号验证
		MemberEntity member = memberService.selectOne(new EntityWrapper<MemberEntity>().setSqlSelect("id", "salt").eq("mobile", form.getMobile()));
		Assert.notNull(member, "此手机号未注册");
		Date now = new Date();
		PhoneCodeEntity phoneCode = phoneCodeService.selectOne(new EntityWrapper<PhoneCodeEntity>().eq("mobile", form.getMobile()).eq("captcha", form.getCaptcha())
				.eq("type", ProjectConstant.PHONECODE_TYPE_FORGOT_PWD).orderBy("create_time", false));
		if (phoneCode == null || phoneCode.getExpireTime().getTime() < now.getTime()) {
			throw new RRException("验证码无效");
		}
		// 使验证码过期
		phoneCodeService.deleteById(phoneCode.getId());

		member.setPassword(DigestUtils.sha256Hex(form.getPassword() + member.getSalt()));
		member.setUpdateTime(now);
		memberService.updateById(member);
		return R.ok();
	}

	public static boolean toTencent(String ticket, String randstr) {
		try {
			SysConfigService config = SpringContextUtils.getBean("sysConfigService", SysConfigService.class);
			String params = "aid=" + config.getValue(ConfigConstant.TENCENT_AID) + "&AppSecretKey=" + config.getValue(ConfigConstant.TENCENT_APP_SECRET_KEY) + "&Ticket=" + ticket
					+ "&Randstr=" + randstr + "&UserIP=" + IPUtils.getIpAddr(HttpContextUtils.getHttpServletRequest());
			String text = HttpClientUtils.sendHttpPost(ConfigConstant.TENCENT_CAPTCHA_URL, params);
			System.out.println("tencent response:" + text);
			int response = JSON.parseObject(text).getInteger("response");
			if (response == 1) {
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}
}
